import React, { useState, useMemo } from 'react';
import { Form, Spin, Space, Button, Tabs } from 'antd';
import { groupBy, keyBy } from 'lodash-es';
import SelectedList from './SelectedList';
import useSelectDevice from './useSelectDevice';
import { useDeviceCategoryTabItems } from '../../hooks';

/**
 * 设备选择
 */
function DeviceSelect(props) {
    const { readOnly, value = [], onChange = () => {}, onDialogOpen = () => {} } = props;

    const [tabKey, setTabKey] = useState();
    const group2ValueMapping = useMemo(() => groupBy(value, 'moduleId'), [value]);
    const cloudRegionId = Form.useWatch('cloudRegionCode', Form.useFormInstance());

    const deviceCategoryTabItems = useDeviceCategoryTabItems({
        onSuccess(data) {
            if (data.length) {
                setTabKey(data[0]['key']);
            }
        },
    });

    const [selectDevice, selectDeviceDialog] = useSelectDevice({
        tabItems: deviceCategoryTabItems.data,
        onSelect(selectedRows) {
            onChange(
                Object.values({
                    ...keyBy(value, 'resourceId'),
                    ...keyBy(selectedRows, 'resourceId'),
                })
            );
        },
    });

    if (deviceCategoryTabItems.loading) return <Spin />;

    if (!deviceCategoryTabItems.data?.length) return '请求设备类别失败';

    const renderActionBar = () => {
        if (readOnly) return null;

        return (
            <Space>
                <Button
                    disabled={!cloudRegionId}
                    onClick={() => {
                        onDialogOpen(value, selectDevice.open);
                    }}
                >
                    添加设备
                </Button>
                <Button
                    disabled={!value.length}
                    onClick={() => {
                        onChange([]);
                    }}
                >
                    清空
                </Button>
            </Space>
        );
    };

    return (
        <Space style={{ display: 'flex' }} direction="vertical" size={10}>
            {renderActionBar()}
            <Tabs
                destroyInactiveTabPane
                type="card"
                activeKey={tabKey}
                items={deviceCategoryTabItems.data.map(({ label, key }) => ({
                    label: `${label}(${group2ValueMapping[key]?.['length'] ?? 0})`,
                    key: key,
                    children: (
                        <SelectedList
                            readOnly={readOnly}
                            modelId={key}
                            dataSource={group2ValueMapping[key]}
                            onDelete={({ cm_unid }) => {
                                const index = value.findIndex((item) => item.resourceId === cm_unid);
                                onChange([...value.slice(0, index), ...value.slice(index + 1)]);
                            }}
                        />
                    ),
                }))}
                onChange={setTabKey}
            />
            {selectDeviceDialog}
        </Space>
    );
}

export default DeviceSelect;
